#define _CRT_SECURE_NO_WARNINGS 1
#define _CRT_SECURE_NO_WARNINGS 1
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl '\n'
const int N = 310;
int n, m, sx, sy;
char g[N][N];
bool vis[N][N];
int dx[] = { -1,1,0,0 };
int dy[] = { 0,0,-1,1 };

struct node {
	int x, y, step;
};

void f(int& nx, int& ny, int step) {
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			if (g[i][j] == g[nx][ny] && (i != nx || j != ny)) {
				nx = i;
				ny = j;
				return;
			}
		}
	}
}

void bfs() {
	queue<node> q;
	q.push({ sx,sy,0 });
	vis[sx][sy] = 1;
	while (!q.empty()) {
		auto t = q.front();
		q.pop();
		if (g[t.x][t.y] == '=') {
			cout << t.step;
			return;
		}
		if (g[t.x][t.y] >= 'A' && g[t.x][t.y] <= 'Z') {
			f(t.x, t.y, t.step);
		}
		for (int i = 0; i < 4; i++) {
			int nx = t.x + dx[i], ny = t.y + dy[i];
			if (nx<1 || nx>n || ny<1 || ny>m) continue;
			if (vis[nx][ny] || g[nx][ny] == '#') continue;
			q.push({ nx,ny,t.step + 1 });
			vis[nx][ny] = 1;
		}
	}
}

int main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cin >> g[i][j];
			if (g[i][j] == '@') {
				sx = i;
				sy = j;
			}
		}
	}
	bfs();
	return 0;
}